package com.xxxy.jsq.action.works;

import com.xxxy.jsq.dao.WorksDao;
import com.xxxy.jsq.model.Works;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/addWorksServlet")
public class addWorksServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public addWorksServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置字符编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 创建 Works 模型对象
        Works model = new Works();
        // 创建 WorksDao 数据访问对象
        WorksDao dao = new WorksDao();

        // 获取页面数据（与前端表单字段名保持一致）
        String worksId = request.getParameter("worksId");
        String typeId = request.getParameter("typeId");
        String worksName = request.getParameter("worksName");
        String worksOrder = request.getParameter("worksOrder");
        String worksFlag = request.getParameter("worksFlag");

        // 设置作品ID（编辑时使用，新增时为空）
        if (worksId != null && !worksId.trim().isEmpty()) {
            model.setWorksId(Long.parseLong(worksId));
        }

        // 设置作品类型ID
        if (typeId != null && !typeId.trim().isEmpty()) {
            model.setTypeId(Long.parseLong(typeId));
        }

        // 设置作品名称（必填项）
        if (worksName != null && !worksName.trim().isEmpty()) {
            model.setWorksName(worksName);
        }

        // 设置作品排序（默认值为0）
        if (worksOrder != null && !worksOrder.trim().isEmpty()) {
            model.setWorksOrder(Integer.parseInt(worksOrder));
        } else {
            model.setWorksOrder(0); // 默认排序为0
        }

        // 设置作品状态（启用/禁用）
        if (worksFlag != null && !worksFlag.trim().isEmpty()) {
            model.setWorksFlag(worksFlag);
        }

        // 调用DAO添加作品
        String result = dao.add(model);

        // 输出结果
        PrintWriter out = response.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 调用 doGet 方法处理 POST 请求
        doGet(request, response);
    }
}
